package io.renren.modules.backstage.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.DayBetween;
import io.renren.common.utils.IdWorker;
import io.renren.common.utils.MyUtils;
import io.renren.modules.backstage.dao.BorrowerDao;
import io.renren.modules.backstage.dao.RepaymentDao;
import io.renren.modules.backstage.dao.RepaymentLogDao;
import io.renren.modules.backstage.entity.BorrowerEntity;
import io.renren.modules.backstage.entity.FormEntity;
import io.renren.modules.backstage.entity.RepaymentEntity;
import io.renren.modules.backstage.entity.RepaymentLogEntity;
import io.renren.modules.backstage.enums.EnumType;
import io.renren.modules.backstage.service.RepaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service("repaymentService")
public class RepaymentServiceImpl implements RepaymentService {
     @Autowired
     RepaymentDao repaymentDao;
     @Autowired
     BorrowerDao borrowerDao;
     @Autowired
     IdWorker idWorker;
     @Autowired
     RepaymentLogDao repaymentLogDao;


    /**
     * 全部结清数据生成接口
     * @param borrowId
     * @param states
     * @return
     */
    @Override
    public List<RepaymentEntity> getByBorrowId(Integer borrowId, Integer states) {
        QueryWrapper<RepaymentEntity> queryWrapper = new QueryWrapper<>();
        if(states==0){
            queryWrapper.eq("borrow_id",borrowId);
            queryWrapper.eq("states",0);
            List<RepaymentEntity> list = repaymentDao.selectList(queryWrapper);
            return list;
        }
        if(states==1){
            queryWrapper.eq("borrow_id",borrowId);
            queryWrapper.eq("states",1);
            QueryWrapper<BorrowerEntity> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("borrow_id",borrowId);
            BorrowerEntity borrowerEntity= borrowerDao.selectOne(queryWrapper1);
            List<RepaymentEntity> list = repaymentDao.selectList(queryWrapper);
            //生成一条结清数据
            RepaymentEntity repaymentEntity = new RepaymentEntity();
            double sumMoney=0;
            double newAccrual=0;
            for (RepaymentEntity entity : list) {
                sumMoney+=entity.getCapital();
                newAccrual+=entity.getAccrual();
            }
            //判断是否已经结清
            if(sumMoney==borrowerEntity.getPrice()){
                //已结清
                //生成新的数据
                repaymentEntity.setDiscpor("您本次贷款已全部结清！！");
                repaymentEntity.setPeriods(0);
                repaymentEntity.setRepayTime(new Date());
                repaymentEntity.setCapital(Double.valueOf(borrowerEntity.getPrice()));
                //保留两位小数
                //保留两位小数
                BigDecimal bg1 = new BigDecimal(newAccrual);
                double f2 = bg1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                repaymentEntity.setAccrual(f2);
                repaymentEntity.setStates(1);
                repaymentEntity.setOverdue(0);
                repaymentEntity.setSumMoney(repaymentEntity.getCapital()+ f2);
                //把提前结清的数据添加到数据库
                list.add(repaymentEntity);
                return list;
            }else{
                //生成IdWork
                Long newPer= idWorker.nextId();
                //转款成Inter
                repaymentEntity.setDiscpor(newPer.toString());
                repaymentEntity.setPeriods(0);
                repaymentEntity.setRepayTime(new Date());
                //保留两位小数
                BigDecimal bg = new BigDecimal(borrowerEntity.getPrice()-sumMoney);
                double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                repaymentEntity.setCapital(f1);
                //保留两位小数
                BigDecimal bg1 = new BigDecimal(0.03*(borrowerEntity.getPrice()-sumMoney));
                double f2 = bg1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                repaymentEntity.setAccrual(f2);
                repaymentEntity.setStates(0);
                repaymentEntity.setOverdue(0);
                repaymentEntity.setSumMoney(f1+f2);
                //把提前结清的数据添加到数据库
                list.add(repaymentEntity);
                return list;
            }
        }
      return null;
    }

    /**
     * 部分还款接口设计
     * @param map
     * @return
     */
    @Override
    public List<RepaymentEntity> saveBuFen(Map<String, Object> map) {
        //获取用户Id
        int userId = Integer.parseInt(JSON.toJSONString(map.get("userId")));
        //获取借款信息
        BorrowerEntity borrowerEntity = JSON.parseObject(JSON.toJSONString(map.get("borrow")), BorrowerEntity.class);
        //获取部分还款金额
        FormEntity forms = JSON.parseObject(JSON.toJSONString(map.get("forms")), FormEntity.class);
        //计算剩余本金
        QueryWrapper<RepaymentEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("borrow_id",borrowerEntity.getBorrowId());
        queryWrapper.eq("states",1);
        List<RepaymentEntity> list = repaymentDao.selectList(queryWrapper);
        // 查出已经还款的期数
        Integer count = repaymentDao.selectCount(queryWrapper);
        double sumMoney=0;
        for (RepaymentEntity entity : list) {
            sumMoney+=entity.getCapital();
            if(entity.getPeriods()==-1){
                count=count-1;
            }
        }
        //计算出剩余的贷还本金
        double sMoney= borrowerEntity.getPrice()-(sumMoney+forms.getMoney());
        int newMoneys=(int) sMoney;
        borrowerEntity.setPrice(newMoneys);

        //调用公共方法生成数据
        List<RepaymentEntity> newList = MyUtils.getThree(borrowerEntity,count);
        //删除之前生成一条数据添加到还款计划表中
        RepaymentEntity repaymentEntity1 = new RepaymentEntity();
        repaymentEntity1.setPeriods(-1);
       repaymentEntity1.setRepayTime(new Date());
       repaymentEntity1.setStates(1);
       repaymentEntity1.setCapital(forms.getMoney()+0.0);
       repaymentEntity1.setAccrual(0.0);
       repaymentEntity1.setOverdue(0);
       repaymentEntity1.setBorrowId(borrowerEntity.getBorrowId());
        //日期格式化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
       repaymentEntity1.setDiscpor("贷款数据ID为"+borrowerEntity.getBorrowId()+
               ",在"+format+"时间部分还款了"+forms.getMoney()+"元");
       repaymentEntity1.setSumMoney(forms.getMoney()+0.0);
       repaymentEntity1.setUserId(userId);
       repaymentDao.insert(repaymentEntity1);

        //查询所有数据进行集合替换
        QueryWrapper<RepaymentEntity> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("borrow_id",borrowerEntity.getBorrowId());
        queryWrapper1.eq("states",0);
        repaymentDao.delete(queryWrapper1);
        //添加新数据
        for (RepaymentEntity repaymentEntity : newList) {
            repaymentDao.insert(repaymentEntity);
        }
        //插入还款日志表数据
        RepaymentLogEntity repaymentLogEntity = new RepaymentLogEntity();
        //设置还款日志金额信息
        repaymentLogEntity.setMoney(forms.getMoney().doubleValue());
        repaymentLogEntity.setUserId(1);
        repaymentLogEntity.setBorrowId(borrowerEntity.getBorrowId());
        repaymentLogEntity.setCreateDate(new Date());
        repaymentLogEntity.setLoanInfo("用户,在"+format+"时间进行了部分还款,还款金额为"+forms.getMoney());
        //添加是数据
        repaymentLogDao.insert(repaymentLogEntity);
        return newList;
    }

    /**
     * 还款成功 修改还款还状态
     * @param repayId
     */
    @Override
    public void updateStatesByRepayId(Integer repayId,Integer overdue,Integer borrowId) {
        //根据借款Id查询借款信息
        QueryWrapper<BorrowerEntity> queryWrapperBorrow = new QueryWrapper<>();
        queryWrapperBorrow.eq("borrow_id",borrowId);
        BorrowerEntity borrowerEntity= borrowerDao.selectOne(queryWrapperBorrow);

        QueryWrapper<RepaymentEntity> queryWrapper = new QueryWrapper<>();
        //预期还款    逾期需缴纳罚息，罚息=逾期本金*逾期天数*日利率*150%
        if(overdue>0){
            queryWrapper.eq("repay_id",repayId);
            RepaymentEntity repaymentEntity = repaymentDao.selectOne(queryWrapper);
            RepaymentEntity repaymentEntity2 = new RepaymentEntity();
            repaymentEntity2.setStates(1);
            //计算时间相差天数
            int day = DayBetween.dayBetween(repaymentEntity.getRepayTime(), new Date());
            //在计算逾期还款利息 罚息=逾期本金*逾期天数*日利率*150%
          if(EnumType.ONE.getEnuTypeName().equals(borrowerEntity.getRepaymentType())){
              //等额本息
              //在计算逾期还款利息 罚息=逾期本金*逾期天数*日利率*150%
              double dayAccrual= repaymentEntity.getCapital()*day*(borrowerEntity.getAnnual()/100/360)*1.5;
              repaymentEntity2.setAccrual(repaymentEntity.getAccrual()+dayAccrual);
          }
            if(EnumType.THREE.getEnuTypeName().equals(borrowerEntity.getRepaymentType())){
                //每次还息一次还本
                repaymentEntity2.setAccrual(repaymentEntity.getAccrual()+5);
            }
            repaymentEntity2.setOverdue(1);
            //日期格式化
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = simpleDateFormat.format(new Date());
            repaymentEntity2.setDiscpor("Id为"+repayId+"的还款款信息,在"+format+"时间逾期还款，将按照规定在本月上增加5个点的利息");
            repaymentDao.update(repaymentEntity2,queryWrapper);
            //插入还款日志表数据
            RepaymentLogEntity repaymentLogEntity = new RepaymentLogEntity();
            repaymentLogEntity.setMoney(repaymentEntity.getCapital()+repaymentEntity2.getAccrual());
            repaymentLogEntity.setUserId(1);
            repaymentLogEntity.setBorrowId(borrowId);
            repaymentLogEntity.setCreateDate(new Date());
            repaymentLogEntity.setLoanInfo("Id为"+repayId+"的还款款信息,在"+format+"时间逾期还款，将按照规定在本月上增加5个点的利息");
            //添加是数据
            repaymentLogDao.insert(repaymentLogEntity);
        }
        //提前还款 减息=逾期本金*逾期天数*日利率*150%
        if(overdue==-1){
            queryWrapper.eq("repay_id",repayId);
            RepaymentEntity repaymentEntity = repaymentDao.selectOne(queryWrapper);
            RepaymentEntity repaymentEntity2 = new RepaymentEntity();
            repaymentEntity2.setStates(1);
            //计算时间相差天数
            int day = DayBetween.dayBetween(new Date(),repaymentEntity.getRepayTime());
            //在计算提前 减息=逾期本金*逾期天数*日利率*150%
            if(EnumType.ONE.getEnuTypeName().equals(borrowerEntity.getRepaymentType())){
                //等额本息
                //在计算提前还款利息 罚息=逾期本金*逾期天数*日利率*150%
                double dayAccrual= repaymentEntity.getCapital()*day*(borrowerEntity.getAnnual()/100/360)*1.5;
                repaymentEntity2.setAccrual(repaymentEntity.getAccrual()-dayAccrual);
            }
            repaymentEntity2.setAccrual(repaymentEntity.getAccrual()-2);
            repaymentEntity2.setOverdue(0);
            //日期格式化
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = simpleDateFormat.format(new Date());
            repaymentEntity2.setDiscpor("Id为"+repayId+"的还款款信息,在"+format+"提前还款，将按照规定在本月上减少2个点的利息");
            repaymentDao.update(repaymentEntity2,queryWrapper);
            //插入还款日志表数据
            RepaymentLogEntity repaymentLogEntity = new RepaymentLogEntity();
            //设置本次还款金额
            repaymentLogEntity.setMoney(repaymentEntity.getCapital()+repaymentEntity2.getAccrual());
            repaymentLogEntity.setUserId(1);
            repaymentLogEntity.setBorrowId(borrowId);
            repaymentLogEntity.setCreateDate(new Date());
            repaymentLogEntity.setLoanInfo("Id为"+repayId+"的还款款信息,在"+format+"进行了提前还款，将按照规定在本月上减少2个点的利息");
            //添加是数据
            repaymentLogDao.insert(repaymentLogEntity);
        }

       if(overdue==0){
           //正常还款
           queryWrapper.eq("repay_id",repayId);
           RepaymentEntity repaymentEntity = new RepaymentEntity();
           repaymentEntity.setStates(1);
           repaymentDao.update(repaymentEntity,queryWrapper);
           //插入还款日志表数据
           RepaymentLogEntity repaymentLogEntity = new RepaymentLogEntity();
           repaymentLogEntity.setMoney(repaymentEntity.getCapital()+repaymentEntity.getAccrual());
           repaymentLogEntity.setUserId(1);
           repaymentLogEntity.setBorrowId(borrowId);
           repaymentLogEntity.setCreateDate(new Date());
           //日期格式化
           SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
           String format = simpleDateFormat.format(new Date());
           repaymentLogEntity.setLoanInfo("用户在"+format+",进行了正常按时间还款");
           //添加是数据
           repaymentLogDao.insert(repaymentLogEntity);
       }

    }

    /**
     * 提前全部结清
     * @param borrowId
     * @param states
     */
    @Override
    public void updateByBorrowId(Integer borrowId, Integer states) {
        //根据ID查询全部未还款数据
        QueryWrapper<RepaymentEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("borrow_id",borrowId);
        queryWrapper.eq("states",0);
        List<RepaymentEntity> repaymentEntityList = repaymentDao.selectList(queryWrapper);
        //调用getByBorrowId方法
        List<RepaymentEntity> list = getByBorrowId(borrowId, states);
        double moneySum=0;
        for (RepaymentEntity repaymentEntity : list) {
            if(repaymentEntity.getPeriods()==0){
                moneySum=repaymentEntity.getSumMoney();
                break;
            }
        }
        //插入还款日志表数据
        RepaymentLogEntity repaymentLogEntity = new RepaymentLogEntity();
        repaymentLogEntity.setUserId(1);
        repaymentLogEntity.setBorrowId(borrowId);
        repaymentLogEntity.setCreateDate(new Date());
        //日期格式化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
        repaymentLogEntity.setLoanInfo("用户在"+format+",已全部结清了本次贷款金额");
        repaymentLogEntity.setMoney(moneySum);
        //添加是数据
        repaymentLogDao.insert(repaymentLogEntity);
        //循环修改状态为已还款
        for (RepaymentEntity repaymentEntity : repaymentEntityList) {
                repaymentEntity.setStates(1);
                repaymentDao.updateById(repaymentEntity);
        }

    }

    @Override
    public List<RepaymentEntity> getUserByBorrowId(String userId) {
        QueryWrapper<RepaymentEntity> repaymentEntityQueryWrapper = new QueryWrapper<>();
        repaymentEntityQueryWrapper.eq("user_id",userId);
        List<RepaymentEntity> repaymentEntities = repaymentDao.selectList(repaymentEntityQueryWrapper);
        return repaymentEntities;
    }

    @Override
    public List<RepaymentEntity> getUserByBorrowId(Integer userId) {
        QueryWrapper<RepaymentEntity> repaymentEntityQueryWrapper = new QueryWrapper<>();
        repaymentEntityQueryWrapper.eq("user_id",userId);
        List<RepaymentEntity> repaymentEntities = repaymentDao.selectList(repaymentEntityQueryWrapper);
        return repaymentEntities;
    }
}
